package org.learn.supports.spring.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;


@Controller
@RequestMapping("/file")
public class FileSystem {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public void upload(MultipartFile file) {

    }


    /**
     * 判断客户端浏览器的方法
     */
    private String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") >= 0) {
                return "IE";
            }
            if (UserAgent.indexOf("firefox") >= 0) {
                return "FF";
            }
            if (UserAgent.indexOf("safari") >= 0) {
                return "SF";
            }
        }
        return null;
    }



    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public void download(@PathVariable("id")String id , HttpServletRequest request, HttpServletResponse response) throws Exception {
        SubjectVo subjectVo = gameSubjectDubboService.findById(Long.valueOf(id));

        try {
            String nameStr = subjectVo.getExcelName();

            String fileName = URLEncoder.encode(nameStr, "utf-8");
            if ("FF".equals(getBrowser(request))) {
                fileName = new String(nameStr.getBytes("utf-8"), "iso-8859-1");
            }
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            //附件下载，不同浏览器是否选择路径不同效果，火狐会选路径
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("utf-8");

            OutputStream os = ExcelUtils.createExcelBuilder(subjectVo.getUrl()).buildToStream(response.getOutputStream());
            os.flush();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
